package com.zzyl.intercept;

import cn.hutool.core.util.ObjectUtil;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.properties.JWTConfigProperties;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.UserThreadLocal;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//1.创建拦截器实现拦截器接口
@Component//交给ioc容器
public class UserInterceptor implements HandlerInterceptor {
    //2.因为解析token需要密钥所以需要注入JWT配置类
    @Autowired//注入jwt配置类
    private JWTConfigProperties jwtConfigProperties;
    //3.拦截前执行操作
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
      //4.获取token
        String token = request.getHeader("authorization");
        //5.判断token是为为空 为空响应401状态码
        if (ObjectUtil.isEmpty(token)) {
            throw new BaseException(BasicEnum.SECURITY_ACCESSDENIED_FAIL);
        }
        //6.解析token  //参数一为密钥 参数二为要解析的token
        Claims claims = JwtUtil.parseJWT(jwtConfigProperties.getBase64EncodedSecretKey(), token);
        //7.判断解析后获得的claims是否为空 为空响应401状态码
        if (ObjectUtil.isEmpty(claims)) {
            throw new BaseException(BasicEnum.SECURITY_ACCESSDENIED_FAIL);
        }
        //8.此时执行到这说明以上没有问题 获取解析后的userid
        Long userid = Long.valueOf((Integer)claims.get("userId"));
        //9.将解析后的id存到线程中
        UserThreadLocal.set(userid);
        //10.判断id是否为空 为空响应401状态码
        if (ObjectUtil.isEmpty(userid)) {
            throw new BaseException(BasicEnum.SECURITY_ACCESSDENIED_FAIL);
        }
        //11，以上都没问题放行
        return true;
    }
    //方法执行完后执行 销毁
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.remove();
    }
}
